const BaseService = require('./baseService')
const { Op } = require('sequelize')
class MenuService extends BaseService {
	constructor(...args) {
		super(...args)
		this.modelName = 'Menu'
	}

	async list(options) {
		return await this.ctx.model[this.modelName].findAll(options)
	}
	async treeMenuByRoleIds(roleIds) {
		// 如果不是数组 转成数组
		if (!Array.isArray(roleIds)) roleIds = [roleIds]
		return await this.ctx.model.RoleMenu.findAll({
			where: {
				role_id: roleIds,
			},
			attributes: {
				exclude: ['menu_id', 'role_id'],
			},
			include: [
				{
					model: this.ctx.model.Menu,
					attributes: {
						exclude: ['createdAt', 'updatedAt', 'deletedAt'],
					},
				},
			],
		})
	}

	async create(obj, uniqueWords) {
		if (uniqueWords) {
			const validateResult = await this.uniqueWordsValiDate(uniqueWords, obj)
			if (!validateResult.flag) {
				return { flag: false, message: validateResult.message }
			}
		}
		const parent_pid = obj.parent_pid

		if (parent_pid !== 0) {
			const IsExisted = this.ctx.model.Menu.findOne({
				id: {
					[Op.eq]: parent_pid,
				},
			})
			if (!IsExisted) {
				return {
					flag: false,
					message: `菜单表中没有id为${parent_pid}的菜单可以做为父级菜单`,
				}
			}
		}
		let createObj = await this.ctx.model.Menu.create(obj)
		if (createObj) {
			return { flag: true, message: `创建成功` }
		} else {
			return { flag: false, message: '创建失败' }
		}
	}
}

module.exports = MenuService
